<template>
	<view class="container-main">
		<view class="container">
			<tui-navigation-bar :isOpacity="false" :maxOpacity="1" @init="initNavigation" :scrollTop="scrollTop"
				backgroundColor="#fff" color="#333" :title="pageTitle">
				<view class="tui-header" :style="{ marginTop: navBarTop + 'px' }">
					<view class="get-back dy-iconfont icon-qiehuanqizuo" @click="goBack"></view>
				</view>
			</tui-navigation-bar>
		</view>
		<view class="main" v-if="loading">
			<view class="appraise">
				<post-item :size="'90rpx'" from="index" :post_type="details.forumType" :basicsWidth="widthrpx"
					:post="details" @clickHead="clickHead" @clickVideo="clickVideo" @share="share" @comment="comment"
					:from="'details'" :isPadLeft="false">
				</post-item>
			</view>
			<view class="post-comment" id="header">
				<view class="header" :class="{'fixed':isTabFixed && 0 < topDistance}">
					<view class="title">评论 {{details.forumCommentNum}}</view>
				</view>
				<!-- -- 评论列表 -- -->
				<comment ref="comment" :list="commentList.list" :padding="padding" @onInfo="onInfo"
					:commentLoad="commentLoad" @getMore="getMore" :commentInfo="details"
					@longpressHandler="longpressHandler" @removeResolve="removeResolve">
				</comment>
			</view>
			<view class="foot">
				<view class="foot-box">
					<view class="foot-input">
						<text @tap.stop.prevent="tapInput" class="input-text">{{inputText || '说点什么…'}}</text>
					</view>
					<view class="foot-input-right">
						<!-- <button class="share" type="default" open-type="share" @tap.stop.prevent="share">分享</button> -->
						<view class="share" @tap.stop.prevent="share(details)">分享</view>
						<view @tap.stop.prevent="onZan" class="comment-zan-no"
							:class="{'comment-zan':details.forumLikeState}">{{details.forumLikeNum | likeNum}}</view>
					</view>
				</view>
			</view>
		</view>
		<uv-popup :safeAreaInsetBottom="false" ref="popupmenu" mode="bottom" round="20" zIndex="2582">
			<view class="delete-pop-menu">
				<view class="menu-list" :class="{'delete':item.lable == 'delete'}"
					v-for="(item,index) in commentMenuList" :key="item.lable"
					@tap.stop.prevent="selectCommentMenu(item)">
					<view>{{item.name}}</view>
				</view>
			</view>
		</uv-popup>
		<comment-foot ref="commentFoot" @onReply="onReply" @changinput="changinput" @footInputClose="footInputClose"
			:placeholder="placeholder"></comment-foot>
		<uv-toast ref="toast"></uv-toast>
		<l-painter ref="painter" hidden />
		<survey-pop></survey-pop>
	</view>
</template>

<script>
	import mp from "@/mixins/mp.js";
	import throttle from '@/uni_modules/uv-ui-tools/libs/function/throttle.js';
	const app = getApp();
	export default {
		mixins: [mp],
		options: {
			styleIsolation: 'shared'
		},
		components: {},
		data() {
			return {
				navBarOpacity: 0, //标题图标距离顶部距离
				scrollTop: 0.5,
				navBarTop: 0,
				pageTitle: '',
				postId: '',
				details: null,
				widthrpx: 0,
				rpx: app.globalData.widthPx / 750,
				commentList: {
					list: [],
					hasMore: false,
					loading: false,
					page: 1,
				},
				commentLoad: {
					loading: false,
					status: 'loading',
					loadingText: '努力加载中',
					nomoreText: '没有更多了'
				},
				loading: false,
				topDistance: 0, //当前菜单距离页面顶部距离
				isTabFixed: false, //菜单是否吸顶
				padding: '60rpx 0',
				shareItem: null,
				inputText: '',
				placeholder: '说点什么...',
				replyinfo: null,
				replyIndex: 0,
				from: null,
				commentMenuList: [{
					name: '复制评论',
					lable: 'copy'
				}],
				longpressInfo: null,
			};
		},
		/**
		 * 计算属性
		 */
		computed: {},
		filters: {
			likeNum(value) {
				if (value > 10000) {
					return (value / 10000).toFixed(2);
				} else {
					return value
				}
			}
		},
		onLoad(options) {
			this.postId = options.id
			console.log(options);
			if (options.from) {
				this.from = options.from
			}
			this.getPageData()
		},
		onShow: function() {
			this.widthrpx = app.globalData.systemInfo.windowWidth / this.rpx - 32 * 2
		},
		onReady: function() {
			setTimeout(() => {
				//获取tab菜单的top
				this.getTabBoxTop();
			}, 500)
		},
		/**
		 * 下拉
		 */
		onPullDownRefresh: function() {
			this.commentList.page = 1
			this.getPageData()
		},
		/**
		 * 触底
		 */
		onReachBottom() {
			if (this.commentList.hasMore && !this.commentList.loading) {
				this.commentLoad.loading = true
				this.getCommentList()
			}
		},
		/**
		 * 滚动
		 */
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			let statusBarHeight = this.mp.statusBarHeight + 44
			if (e.scrollTop > (this.topDistance - statusBarHeight)) {
				this.isTabFixed = true
			} else {
				this.isTabFixed = false
			}
		},
		onShareAppMessage: function() {
			const that = this;
			//转发参数
			return {
				// 转发的标题
				title: this.details.content,
				desc: 'PENG一下，趣收获',
				// 转发的路径，默认是当前页面，必须是以‘/’开头的完整路径，/pages/index/index
				path: '/page_community/details/details?id=' + that.postId + '&from=share',
				//自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，
				//支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
				imageUrl: that.details.forumPictureList[0].coverPictureUrl || that.details.forumPictureList[0].fileUrl
			}
		},
		// 分享到朋友圈
		onShareTimeline() {
			//转发参数
			return {
				// 转发的标题
				title: this.details.content,
				desc: 'PENG一下，趣收获',
				// 转发的路径，默认是当前页面，必须是以‘/’开头的完整路径，/pages/index/index
				path: '/page_community/details/details?id=' + that.postId + '&from=share',
				//自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，
				//支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
				imageUrl: that.details.forumPictureList[0].coverPictureUrl || that.details.forumPictureList[0].fileUrl
			}
		},
		methods: {
			goLogin() {
				app.doLogin()
			},
			initNavigation(e) {
				this.navBarOpacity = e.opacity;
				this.navBarTop = e.top;
			},
			// 分享开始 ----------------------------------
			getShareCode(id) {
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/qr/create-wx-code", {
							envVersion: 'release',
							forumId: id,
							path: "page_community/details/details?id=" + id + '&from=share',
						},
						(result) => {
							let res = result.data
							resolve(res);
						}, null, () => {
							resolve(false);
						}
					);
				});
			},
			async share(e) {
				console.log(e);
				let that = this
				that.$refs.toast.show({
					type: 'loading',
				})
				const shareCode = await that.getShareCode(e.id)
				that.mp.poster.views[1].views[0].src = e.avatar
				that.mp.poster.views[1].views[1].text = e.nickName
				that.mp.poster.views[1].views[3].text = e.cityName
				that.mp.poster.views[2].views[0].text = e.content
				that.mp.poster.views[3].views[0].src = shareCode.url

				if (!e.forumPictureList) {
					that.mp.poster.css.height = "462rpx"
					that.mp.poster.css.padding = "56rpx 47rpx 16rpx 38rpx"
					that.mp.poster.css.backgroundImage =
						'url("https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/poser-bg-w2.png")'
					that.mp.poster.views[0].css.width = "0"
					that.mp.poster.views[0].css.height = "0"
					that.mp.poster.views[0].css.marginBottom = "0"
					that.mp.poster.views[1].css.marginBottom = "50rpx"
				} else {
					that.mp.poster.css.height = "1039rpx"
					that.mp.poster.css.padding = "64rpx 38rpx 16rpx 38rpx"
					that.mp.poster.css.backgroundImage =
						'url("https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/poser-bg-h2.png")'
					that.mp.poster.views[0].css.width = "576rpx"
					that.mp.poster.views[0].css.height = "576rpx"
					that.mp.poster.views[0].css.marginBottom = "46rpx"
					that.mp.poster.views[0].src = e.forumPictureList[0].coverPictureUrl ? e.forumPictureList[0]
						.coverPictureUrl : e.forumPictureList[0].fileUrl
				}
				// 渲染
				that.$refs.painter.render(that.mp.poster);
				// 生成图片
				that.$refs.painter.canvasToTempFilePathSync({
					fileType: "jpg",
					// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
					pathType: 'url',
					quality: 1,
					success: (res) => {
						that.$refs.toast.hide()
						wx.showShareImageMenu({
							path: res.tempFilePath,
							success: () => {},
						})
					},
					fail: () => {
						that.$refs.toast.hide()
					}
				});
			},
			// 分享结束 ----------------------------------
			// 长按
			longpressHandler(e) {
				this.longpressInfo = e
				console.log(e);
				if (e.delete_status) {
					this.$set(this.commentMenuList, 1, {
						name: '删除',
						lable: 'delete'
					})
				} else {
					this.commentMenuList.splice(1, 1)
				}
				this.$refs.popupmenu.open();
			},
			selectCommentMenu(item) {
				let that = this
				if (item.lable == 'copy') {
					uni.setClipboardData({
						data: that.longpressInfo.item.comment,
						showToast: false,
						success: function() {
							that.$refs.popupmenu.close();
							that.$refs.toast.show({
								type: 'default',
								message: "复制成功"
							})
							setTimeout(() => {
								that.$refs.toast.hide()
							}, 1000)
						}
					});
				} else if (item.lable == 'delete') {
					that.$refs.comment.deleteComment()
				}
			},
			removeResolve() {
				let that = this
				that.$refs.popupmenu.close();
				that.$refs.toast.show({
					type: 'default',
					message: "删除成功"
				})
				setTimeout(() => {
					that.$refs.toast.hide()
				}, 1000)
			},

			// 加载页面数据
			getPageData: function(callback) {
				Promise.all([this.getUserDetails(), this.getCommentList()]).then(() => {
					this.increaseViews()
					uni.stopPullDownRefresh();
					this.loading = true
					callback && callback()
				}).catch(() => {
					uni.stopPullDownRefresh();
					this.loading = true
					callback && callback()
				});
			},

			//获取动态详情
			getUserDetails() {
				return new Promise((resolve, reject) => {
					app._get(
						"/client/forum-topic/forum-detail", {
							forumId: this.postId,
						},
						(result) => {
							result.data.animation = false
							result.data.vanish_animation = false
							result.data.type = 'post'
							this.placeholder = '说点什么...'
							this.details = result.data;
							this.replyinfo = this.details
							this.pageTitle = result.data.nickName
							resolve();
						}, null, () => {
							reject();
						}
					);
				});
			},
			// 增加浏览量
			increaseViews(e) {
				return new Promise((resolve, reject) => {
					app._post_form("/client/forum-topic/submit-forum-view", {
							"list": [{
								"forumId": this.postId,
								"topicId": this.details.topicId
							}]
						},
						(result) => {
							resolve();
						}, null, () => {
							reject();
						}
					);
				});
			},

			// 评价开始 ------------------------------------------------------------

			clickVideo() {},

			clickHead(e) {
				app.navigationTo('page_sharing/accompany/details?id=' + e.userId + '&from=1')
			},

			// 子评论列表查询
			getMore(e) {
				this.$set(this.commentList.list[e.index], 'clientForumCommentPage', e)
			},
			// 评论列表查询
			getCommentList(id) {
				return new Promise((resolve, reject) => {
					this.commentList.loading = false
					app._post_form("/client/forum-comment/query-page", {
							current: this.commentList.page,
							extra: {},
							model: {
								forumId: this.postId,
							},
							order: "descending",
							size: 10,
							sort: "createTime"
						},
						(result) => {
							let {
								records,
								total
							} = result.data;
							let {
								page,
								list,
								hasMore
							} = this.commentList;
							if (1 == page) {
								list.length = 0;
							}
							records.forEach((item, index) => {
								item.clientForumCommentPage = {
									list: item.clientForumCommentPageVO ? [item
										.clientForumCommentPageVO
									] : [],
									hasMore: item.commentNum > 1 ? true : false,
									loading: false,
									page: 1,
									index: 0
								}
							})

							list = [...list, ...records];
							hasMore = total > list.length;
							if (hasMore) {
								page++;
								this.commentLoad.loading = false
							} else if (list.length > 3) {
								this.commentLoad.loading = true
								this.commentLoad.status = 'nomore'
							} else {
								this.commentLoad.status = 'nomore'
							}
							this.commentList.hasMore = hasMore;
							this.commentList.list = list;
							this.commentList.page = page;
							resolve();
						}, null, () => {
							reject();
						}
					);
				});
			},

			// 关闭评价列表弹窗
			closePop() {
				this.$refs.popup.close();
			},
			// 点表情
			tapEmoji() {
				this.$refs.commentFoot.tapEmoji();
			},
			// 点输入框block
			tapInput() {
				this.replyinfo = this.details
				this.$refs.commentFoot.tapInput();
			},
			// 点用户回复
			onInfo(e) {
				if (e.index) {
					this.replyIndex = e.index
				}
				this.replyinfo = e.item
				this.placeholder = '回复@' + e.item.userName
				this.$refs.commentFoot.tapInput();
			},
			// 用户输入
			changinput(e) {
				this.inputText = e
			},
			// 输入框弹窗关闭
			footInputClose() {
				if (!this.inputText) {
					setTimeout(() => {
						this.placeholder = '说点什么...'
					}, 200)
				}
			},
			// 回复内容校验
			validMessages(str) {
				var re = /\S/
				return re.test(str)
			},
			// 回复
			onReply(e) {
				let that = this
				if (!that.validMessages(that.inputText)) {
					that.$refs.toast.show({
						type: 'default',
						message: "请输入回复内容"
					})
					setTimeout(() => {
						that.$refs.toast.hide()
					}, 1000)
					return
				}
				if (!e) {
					that.$refs.toast.show({
						type: 'default',
						message: "输入文字不合法"
					})
					setTimeout(() => {
						that.$refs.toast.hide()
					}, 1000)
					return
				}
				that.$refs.toast.show({
					type: 'loading',
				})
				throttle(app._post_form('/client/forum-topic/submit-comment', {
					comment: that.inputText,
					commentType: that.replyinfo.type == 'comment' ? 0 : 1,
					forumId: that.replyinfo.type == 'comment' ? that.replyinfo.forumId : that.replyinfo.id,
					commentId: that.replyinfo.type == 'comment' ? that.replyinfo.commentId : null,
				}, (result) => {
					let data = Object.assign(result.data, {
						clientForumCommentPage: {
							list: [],
							hasMore: true,
							loading: false,
							page: 1,
							index: 0
						}
					})
					that.inputText = ''
					that.$refs.commentFoot.changinputSec()
					uni.hideKeyboard();
					that.$refs.toast.show({
						type: 'default',
						message: "评论成功"
					})
					setTimeout(() => {
						that.$refs.toast.hide()
					}, 1000)
					if (that.replyinfo.type == 'post') {
						uni.pageScrollTo({
							scrollTop: 0,
							duration: 150
						});
						this.details.forumCommentNum = Number(this.details.forumCommentNum) + 1
						data.commentNum = 0
						that.commentList.list.unshift(data)
					} else {
						this.details.forumCommentNum = Number(this.details.forumCommentNum) + 1
						that.commentList.list[that.replyIndex].commentNum = Number(that.commentList.list[that
							.replyIndex].commentNum) + 1
						that.commentList.list[that.replyIndex].clientForumCommentPage.list.unshift(data)
					}
				}, null, (err) => {
					that.inputText = ''
					that.$refs.commentFoot.changinputSec()
					that.$refs.toast.hide()
				}), 1000, true)
				// if()
			},
			onZan() {
				this.topicUpvote()
			},
			topicUpvote(post, index) {
				if (!app.globalData.isLogin) {
					this.details.forumLikeNum = this.details.forumLikeState == 1 ? Number(this.details.forumLikeNum) - 1 :
						Number(this.details.forumLikeNum) + 1
					this.details.forumLikeState = this.details.forumLikeState == 1 ? 0 : 1
					return
				}
				return new Promise((resolve, reject) => {
					app._post_form('/client/forum-topic/give-like', {
						giveId: this.details.id,
						giveType: 0
					}, (result) => {
						this.details.forumLikeNum = this.details.forumLikeState == 1 ? Number(this.details
								.forumLikeNum) - 1 :
							Number(this.details.forumLikeNum) + 1
						this.details.forumLikeState = this.details.forumLikeState == 1 ? 0 : 1
						resolve()
					}, null, (err) => {})
				})
			},
			// 评价结束 ------------------------------------------------------------
			getTabBoxTop() {
				let _this = this;
				uni.getSystemInfo({
					success: result => {
						let query = uni.createSelectorQuery().in(this);
						query.select('#header').boundingClientRect();
						query.selectViewport().scrollOffset();
						query.exec(function(res) {
							console.log(res);
							_this.topDistance = res[0].top;
						})
					}
				})
			},
			// 返回上一页
			goBack: function() {
				if (this.from == 'share') {
					uni.switchTab({
						url: '/pages/index/index'
					})
				} else {
					app.beNavigateBack();
				}
			},
			//---
		},
	};
</script>
<style lang="scss" scoped>
	.container-main {
		background: #FFFFFF;
		min-height: 100vh;
	}

	.container {
		// padding-bottom: constant(safe-area-inset-bottom);
		// padding-bottom: env(safe-area-inset-bottom);

		.tui-header {
			width: 100%;
			position: fixed;
			top: 0;
			padding: 0 42rpx;
			display: flex;
			align-items: center;
			height: 32px;
			transform: translateZ(0);
			z-index: 99999;
			box-sizing: border-box;

			.get-back {
				display: flex;
				align-items: center;
				justify-content: center;
				flex-shrink: 0;
				width: 36rpx;
				height: 36rpx;
				color: #000;
				font-size: 36rpx;
				background: rgba(255, 255, 255, 0.6);
				border-radius: 50%;
				padding: 10rpx;
			}
		}
	}

	.main {
		box-sizing: border-box;
		padding: 212rpx 32rpx 0;
		/* #ifdef H5 */
		padding-top: calc(212rpx - 88rpx);
		/* #endif */
		padding-bottom: calc(132rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(132rpx + env(safe-area-inset-bottom));

		.appraise {
			padding-bottom: 36rpx;
			box-sizing: border-box;

			/deep/.post {
				.other-functions {
					margin: 28rpx 0;
				}
				.operate-fun{
					display: flex;
				}

				.topic {
					margin-bottom: 0;
				}

				.class-heading {
					width: 100%;
				}
			}

		}

		.post-comment {
			.header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				box-sizing: border-box;
				padding-bottom: 36rpx;
				background: #FFFFFF;
				width: 100%;

				// &.fixed {
				// 	position: fixed;
				// 	top: 44px;
				// 	z-index: 3;
				// 	padding-bottom: 0;
				// }

				.title {
					font-size: 32rpx;
					font-weight: 900;
					color: #282D2D;
					line-height: 45rpx;
				}
			}
		}

		.foot {
			box-shadow: 0px 0 9rpx 0px rgba(198, 204, 202, 0.56);
			position: fixed;
			background: #FFFFFF;
			width: 100vw;
			bottom: 0;
			left: 0;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);

			.foot-box {
				box-sizing: border-box;
				padding: 22rpx 36rpx;
				background: #FFFFFF;
				height: 120rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				&.foot-input-pop {
					position: relative;
					transition: bottom 300ms ease-out 0ms, -webkit-transform 300ms ease-out 0ms, transform 300ms ease-out 0ms;
					transform-origin: 50% 50%;
				}

				.foot-input {
					box-sizing: border-box;
					padding: 12rpx 36rpx;
					height: 76rpx;
					background: #F6F8F7;
					border-radius: 39rpx;
					font-size: 28rpx;
					font-weight: 400;
					color: #999B9B;
					line-height: 40rpx;
					margin-right: 40rpx;
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.input-text {
						flex: 1;
					}

					.icon-xingzhuangjiehebeifen {
						color: #282D2D;
						font-size: 40rpx;
						padding-left: 30rpx;
					}
				}

				.foot-input-right {
					display: flex;

					.share {
						margin: 0;
						padding: 0;
						background: none;
						font-size: 20rpx;
						font-weight: 400;
						color: #282D2D;
						line-height: 28rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						padding-right: 50rpx;

						&::before {
							// content: "";
							// display: block;
							// width: 42rpx;
							// height: 42rpx;
							// background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/zhuanfa.png');
							// background-size: 100% 100%;
							// margin-bottom: 4rpx;
							// flex-shrink: 0;
							font-family: "dy-iconfont";
							content: "\e8b0";
							font-size: 48rpx;
							line-height: 44rpx;
							width: 44rpx;
							height: 44rpx;
							box-sizing: border-box;
							flex-shrink: 0;
						}
					}

					.comment-zan-no {
						font-size: 20rpx;
						font-weight: 400;
						color: #282D2D;
						line-height: 28rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						filter: grayscale(100%);
						-webkit-filter: grayscale(100%);

						&::before {
							font-family: "dy-iconfont";
							content: "\e635";
							font-size: 48rpx;
							line-height: 44rpx;
							width: 44rpx;
							height: 44rpx;
							box-sizing: border-box;
							flex-shrink: 0;
						}


						&.comment-zan {
							filter: grayscale(0%);
							-webkit-filter: grayscale(0%);

							&::before {
								content: "";
								display: inline-block;
								box-sizing: border-box;
								width: 44rpx;
								height: 44rpx;
								background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/zan/zan.png');
								background-size: 100% 100%;
								flex-shrink: 0;
							}
						}

					}
				}
			}
		}
	}

	.delete-pop-menu {
		background: #FFFFFF;
		box-sizing: border-box;
		padding: 0 25rpx 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		position: relative;

		.menu-list {
			padding: 38rpx 0;
			position: relative;
			font-size: 32rpx;
			font-weight: 400;
			color: #282D2D;
			line-height: 45rpx;
			border-bottom: 2rpx solid #E3E9E5;
			// display: flex;
			text-align: center;

			&.delete {
				color: #FF4664;
			}

			&:last-child {
				border: none;
			}

			.dy-iconfont {
				margin-right: 25rpx;
			}
		}
	}
</style>